<?php 
/**
 * 用于微擎版本数据升级到0.2版
 * 
 * [WeEngine System] Copyright (c) 2013 WE7.CC
 */
require './source/bootstrap.inc.php';
define('IMS_UPDATE_VERSION', '0.2');
$actions = array('', 'show_description', 'database_struct', 'database_data', 'cleanup', 'finish');
$action = $action = in_array($_GET['action'], $actions) ? $_GET['action'] : '';
$step = max(intval($_GET['step']), 1);

if (empty($action)) {
	$action = isset($actions[$step]) ? $actions[$step] : '';
} else {
	$step = array_keys($actions, $action);
}

if (file_exists(IA_ROOT . '/data/update.lock') && $action != 'finish') {
	exit('请删除“data/update.lock”文件后运行此升级文件！');
}

if (IMS_VERSION > IMS_UPDATE_VERSION) {
	exit('你当前使用的版本为'.IMS_VERSION.'，无需使用此升级程序！');
}
header('Content-Type: text/html; charset=utf-8');
if ($action == 'show_description') {
?>
<p>本程序用于“微擎 - 微信公众平台自助引擎”v<?php echo IMS_UPDATE_VERSION ?> 版本数据升级用。</p>
<p>升级前请强烈建议您备份好数据！确认升级请点击<a href="?step=2">“开始升级”</a></p>
<?php 
} elseif ($action == 'database_struct') {
	$sql = <<<EOF
CREATE TABLE IF NOT EXISTS `ims_log_message` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `weid` int(11) NOT NULL COMMENT '微信号ID，关联wechats表',
  `from_user` varchar(50) NOT NULL COMMENT '用户的唯一身份ID',
  `lastupdate` int(10) unsigned NOT NULL COMMENT '用户最后发送信息时间',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `ims_music_reply` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `rid` int(10) unsigned NOT NULL COMMENT '规则ID',
  `title` varchar(50) NOT NULL DEFAULT '' COMMENT '标题',
  `description` varchar(255) NOT NULL DEFAULT '' COMMENT '介绍',
  `url` varchar(300) NOT NULL DEFAULT '' COMMENT '音乐地址',
  `hqurl` varchar(300) NOT NULL DEFAULT '' COMMENT '高清地址',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
EOF;
	runquery($sql);
	$sql = <<<EOF
ALTER TABLE `ims_wechats` ADD `default_period` TINYINT UNSIGNED NOT NULL COMMENT '回复周期时间' AFTER `default` ;
ALTER TABLE `ims_wechats_modules` ADD `displayorder` TINYINT( 1 ) NOT NULL DEFAULT '-1' COMMENT '优先级';
ALTER TABLE `ims_modules` ADD `issystem` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '0' COMMENT '是否是系统模块';
ALTER TABLE `ims_basic_reply` CHANGE `content` `content` VARCHAR( 1000 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;
EOF;
	runquery($sql);
?>
	<p>数据库结构更新完成，正在进行数据更新！如果浏览器未自动跳转，请点击<a href="?step=3">“下一步”</a></p>
	<script type="text/javascript">
		setTimeout(function(){
			location.href = '?step=3';
		}, 2000);
	</script>
<?php 
} elseif ($action == 'database_data') {
	$sql = <<<EOF
INSERT INTO `ims_modules` (`mid`, `name`, `title`, `ability`, `description`, `rulefields`, `settings`, `issystem`) VALUES (4, 'music', '基本语音回复', '提供语音、音乐等音频类回复', '在回复规则中可选择具有语音、音乐等音频类的回复内容，并根据用户所设置的特定关键字精准的返回给粉丝，实现一问一答得简单对话。', 1, '', 1);
INSERT INTO `ims_modules` (`mid`, `name`, `title`, `ability`, `description`, `rulefields`, `settings`, `issystem`) VALUES (5, 'wxapi', '乐享接口回复', '乐享微信营销管理平台与微擎管理系统的兼容服务', '微擎将试水与第三方管理平台进行战略融合，更好的服务于广大的微信公众平台用户。微擎内置模块的优先级高于其他平台接口，微擎无法处理的对话内容将交于第三方平台处理。', 0, '', 0);
UPDATE `ims_modules` SET `issystem` = '1' WHERE `name` = 'basic' OR `name` = 'news' OR `name` = 'music';
UPDATE `ims_wechats_modules` SET `displayorder` = '-1' WHERE mid = 1 OR mid = 2 OR mid = 4;
EOF;
	runquery($sql);
?>
	<p>数据库数据更新完成，正在进行数据清理！如果浏览器未自动跳转，请点击<a href="?step=4">“下一步”</a></p>
	<script type="text/javascript">
		setTimeout(function(){
			location.href = '?step=4';
		}, 2000);
	</script>
<?php 	
} elseif ($action == 'cleanup') {
	$sql = <<<EOF
ALTER TABLE `ims_modules` DROP `enabled`;
DELETE FROM `ims_cache` WHERE `key` = 'setting:wechats';
DELETE FROM `ims_cache` WHERE `key` LIKE 'setting:modules:%';
EOF;
	runquery($sql);
	rmdirs(IA_ROOT . '/data/tpl/default', true);
?>
	<p>数据清理完成！如果浏览器未自动跳转，请点击<a href="?step=5">“下一步”</a></p>
	<script type="text/javascript">
		setTimeout(function(){
			location.href = '?step=5';
		}, 2000);
	</script>
<?php 
} elseif ($action == 'finish') {
	touch(IA_ROOT . '/data/update.lock');
	exit('升级完成！<a href="index.php">体验微擎</a>');
}

function runquery($sql) {
	global $_W;
	$dbprefix = $_W['config']['db']['tablepre'];
	if(!isset($sql) || empty($sql)) return;

	$sql = str_replace("\r", "\n", str_replace(' ims_', ' '.$dbprefix, $sql));
	$sql = str_replace("\r", "\n", str_replace(' `ims_', ' `'.$dbprefix, $sql));

	$ret = array();
	$num = 0;
	foreach(explode(";\n", trim($sql)) as $query) {
		$ret[$num] = '';
		$queries = explode("\n", trim($query));
		foreach($queries as $query) {
			$ret[$num] .= (isset($query[0]) && $query[0] == '#') || (isset($query[1]) && isset($query[1]) && $query[0].$query[1] == '--') ? '' : $query;
		}
		$num++;
	}
	unset($sql);
	foreach($ret as $query) {
		$query = trim($query);
		if($query) {
			pdo_query($query);
		}
	}
}

